package org.example.service;

import lombok.extern.slf4j.Slf4j;
import org.example.engine.MatchEngine;
import org.example.order.CmdPack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CmdPackService {

    @Autowired
    MatchEngine matchEngine;

    private final BlockingQueue<CmdPack> cmdPackCache = new LinkedBlockingDeque<>();

    public void addCmdPack(CmdPack cmdPack) {
        cmdPackCache.add(cmdPack);
    }

    @PostConstruct
    public void init() {
        new Thread() {
            @Override
            public void run() {
                while(true) {
                    try {
                        CmdPack pack = cmdPackCache.poll(50, TimeUnit.MILLISECONDS);
                        if(pack != null){
                            process(pack);
                        }
                    } catch (InterruptedException e) {
                        log.error("获取cmdpack超时");
                    }
                }
            }
        }.start();
    }

    private long lastPackNo = -1;
    private void process(CmdPack pack) {
        long packNo = pack.getPackNo();
        if(lastPackNo == -1 || packNo == lastPackNo+1) {
            pack.getOrderCmds().forEach(cmd -> {
                matchEngine.submit(cmd);
            });
        }else {
            System.out.println("处理收到cmdPack时出错。。。。");
            //TODO 处理包号不一致的情况
            //1, 获取以前的包号
            //2, 获取靠后的包号
        }
    }

}
